<template>
  <view class="m-home">
    <!--切换-->
    <view v-if="appId !== 'wxdfa6fd6c0f1c4fc7'" class="m-home-header">
      <x-navigation-bar id="ref-home-header" search category />
    </view>
    <view class="m-home-swiper">
      <!--商城-->
      <view class="m-home-swiper-item m-home-mall">
        <view :style="'height:'+ homeHeaderHeight +'px'" class="header-placeholder" />
        <scroll-view
          :style="[pageStyle]"
          :refresher-triggered="refresherTriggered"
          :scroll-top="scrollViewTop"
          scroll-y
          enhanced
          refresher-enabled
          class="mall"
          @scroll="handlePageScrollView"
          @dragend="handleDragEnd"
          @scrolltoupper="handlePageScrollToupper"
          @scrolltolower="handleReachBottom"
          @refresherrefresh="handlePullDownRefresh"
        >
          <h-pages-module
            v-if="componentList"
            ref="h-pages-module"
            :isHome="true"
            :query="query"
            :title="title"
            :componentList="componentList"
            :navigationHeight="navigationHeight"
            isLoaded
          />
        </scroll-view>
      </view>
    </view>

    <!--定向弹窗-->
    <x-pop-box :query="query" v-if="isPopBox" :trigger-type="triggerType" />

    <!--限时优惠-->
    <x-time-discount :visible.sync="showDiscountBack" />

    <!--置顶-->
    <view class="m-customer-service">
      <view class="btn" @click="scrollTop">
        <view class="slot">
          <x-icon name="icon-036" size="34" color="#ED6A0C"/>
          <text class="_text">置顶</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { mapState } from 'vuex';
import $config from '@/config';
import XNavigationBar from '@/components/x-navigation-bar';
import XTimeDiscount from '@/components/x-time-discount';
import XIcon from '@/components/x-icon';
import XPopBox from '@/components/x-pop-box';
import HPagesModule from '@/components/h-pages-module';

// 滑动结束防抖计时
let dragendTime = null;
// 页面滑动位置
let pageScrollTop = 0;

export default {
  name: 'Home',
  components: {
    XNavigationBar,
    XTimeDiscount,
    XPopBox,
    HPagesModule,
    XIcon
  },
  props: {},
  data() {
    return {
      isSaas: $config.project === 'saas',
      appId: $config.appId,
      query: {
        source: 'mall'
      },
      title: '首页',
      // 顶部切换栏高
      homeHeaderHeight: 0,
      // 定向弹窗状态
      isPopBox: false,
      // 商城滚动条位置
      scrollViewTop: 0,
      // 商城模块
      componentList: null,
      // 商城页面样式
      pageStyle: {},
      // 是否显示限制优惠
      showDiscountBack: false,
      // 设置当前下拉刷新状态，true 表示下拉刷新已经被触发，false 表示下拉刷新未被触发
      refresherTriggered: false,
      // 逛逛当前切换到的商品
      currentProduct: null
    };
  },
  computed: {
    ...mapState({
      homeReLaunchUrl: state => state['product'].homeReLaunchUrl
    }),
    // 定向弹窗口类型
    triggerType() {
      return this.isSaas ? 2 : 1;
    }
  },
  onLoad() {
    this.getHomeData();

    // 延迟加载定向弹窗
    setTimeout(() => {
      this.isPopBox = true;
      // 小程序版本更新提示
      try {
        const updateManager = wx.getUpdateManager();
        updateManager.onUpdateReady(() => {
          wx.showModal({
            title: '更新提示',
            content: '新版本已经准备好，是否重启应用？',
            success: (res) => {
              if (res.confirm) {
                // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                updateManager.applyUpdate();
                // 更新小程序
                this.$XTrack('updateAppEvent');
              }
            }
          });
        });
      } catch (e) {
        console.log(e);
      }
    }, 1000);
  },
  onShow() {
    if (this.homeReLaunchUrl) {
      this.showDiscountBack = true;
    }
    // 再次返回页面的时候，更新缓存中的数据
    this.$XTrack('onLoad', this.query);
    // 更新store访问数据
    this.$store.dispatch('pages/fetchAppStore');

    // 逛逛
    const ref = this.$refs['ref-page-walk'];
    if (ref) {
      ref.handleShow();
    }

    // 校验设备，如果是pc端，那么跳转到错误界面
    uni.getSystemInfo({
      success: (res) => {
        if (['windows', 'mac'].includes(res.platform)) {
          uni.reLaunch({
            url: '/pages/error/index'
          });
        }
      }
    });
  },
  // 用户点击右上角分享
  onShareAppMessage() {
    this.$XTrack('onShareAppMessage');
    return {
      title: $config.appName
    };
  },
  mounted() {
    this.getHomeHeaderHeight();
  },
  methods: {
    getHomeData() {
      if (this.isSaas) {
        this.getStoreInfo();
      } else {
        this.getModule();
      }
    },
    // 获取顶部切换栏高
    getHomeHeaderHeight() {
      const query = uni.createSelectorQuery();
      query.select('#ref-home-header').boundingClientRect(data => {
        this.homeHeaderHeight = data ? data.height : 0;
      }).exec();
    },
    // 下拉刷新
    handlePullDownRefresh() {
      this.refresherTriggered = true;
      this.getHomeData();
      this.$refs['h-pages-module']?.handleRefresh();
    },
    // 商城页滚动到底部
    handleReachBottom() {
      this.$refs['h-pages-module']?.handleReachBottom();
    },
    // 回到顶部
    scrollTop() {
      pageScrollTop = 0;
      this.scrollViewTop = 1;
    },
    getStoreInfo() {
      this.$http({
        login: true,
        url: '/account/store/base/info',
        method: 'get',
        report: false
      }).then(res => {
        if (res.data.homePageId) {
          this.getModule();
        } else {
          this.componentList = [{
            type: 7,
            templateType: 19,
            componentStyle: {}
          }];
          this.refresherTriggered = false;
        }
      });
    },
    // 加载首页模块配置信息
    getModule() {
      this.$http({
        login: true,
        alarm: true,
        isCancelToken: true,
        url: this.isSaas ? '/product/store/page/app/detail' : '/product/home/page/app/detail'
      }).then(res => {
        const data = res.data;
        if (data) {
          this.$XTrack('push', {
            pageId: res.data.id
          });
          res.data.componentList?.forEach((item) => {
            item.componentStyle = JSON.parse(item.componentStyle);
            item.componentContentList?.forEach((it) => {
              it.contentStyle = JSON.parse(it.contentStyle);
            });
          });
          const orderComponent = res.data.componentList.find((item) => { return item.type === 5; });
          if (orderComponent && orderComponent.templateType === 15) {
            const orderIndex = res.data.componentList.findIndex((item) => { return item.type === 5; });
            res.data.componentList.splice(orderIndex, 1);
            res.data.componentList.unshift(orderComponent);
          }
          const waterfallIndex = res.data.componentList.findIndex(this.objFn);
          res.data.componentList.push(res.data.componentList[waterfallIndex]);
          res.data.componentList.splice(waterfallIndex, 1);

          this.componentList = res.data.componentList;
          this.pageStyle = JSON.parse(res.data.pageStyle);
          this.title = res.data.title;
          this.refresherTriggered = false;
        }
      }).catch(() => {
        this.refresherTriggered = false;
        setTimeout(() => {
          this.getHomeData();
        }, 800);
      });
    },
    objFn(obj) {
      return obj.type === 7;
    },
    // 切换视频
    handleProductChange(res) {
      this.currentProduct = res;
    },
    // 刷新分享统计
    setShareCount() {
      const ref = this.$refs['ref-page-walk'];
      if (ref) {
        ref.setShareCount();
      }
    },
    // 商品内容滑动
    handlePageScrollView({ detail }) {
      const { scrollTop } = detail;
      pageScrollTop = scrollTop;
    },
    // 滚动到顶部/左边时触发
    handlePageScrollToupper() {
      pageScrollTop = 0;
    },
    // 滑动结束，有bug
    handleDragEnd() {
      if (dragendTime) {
        clearTimeout(dragendTime);
      }
      dragendTime = setTimeout(() => {
        this.scrollViewTop = pageScrollTop;
        dragendTime = null;
        // console.log('滑动结束-设置滚动条位置', pageScrollTop)
      }, 1800);
    },
    // 页面跳转
    handleNavigateTo(url) {
      uni.navigateTo({
        url
      });
    }
  }
};
</script>

<style lang="scss">
.m-home{
  width: 100%; height: 100vh; position: relative; overflow: hidden;
  .m-home-swiper{
    height: 100%; width: 100%; overflow: hidden; position: absolute; left: 0; top: 0; display: flex; transition: .3s;
  }
  .m-home-swiper-item{ flex: 1; height: 100%; position: relative;}
  .m-home-walk{ background-color: #000;}
}
.m-home-mall{
  display: flex; flex-direction: column; overflow: hidden;
  .header-placeholder{ width: 100%;}
  .header{
    display: flex; align-items: center; padding: 20px 0 20px 24px; background-color: #fff;
    .search{
      flex: 1; display: flex; align-items: center; border: 2px solid #EC2727; height: 64px; background-color: #F4F4F4; border-radius: 10px; color: #646464; padding: 0 20px;
      .placeholder{ flex: 1; font-size: 28px; padding: 0 10px;}
      .button{ color: #EB441F; font-size: 28px;}
    }
    .category{
      display: flex; flex-direction: column; justify-content: center; align-items: center; line-height: 1; padding: 0 24px;
      text{ font-size: 24px; color: #333333;}
    }
  }
  .mall{ flex: 1; position: relative; overflow: hidden;}
}
.m-customer-service{
  position: fixed; right: 40px; bottom: 160px;
  .btn{
    width: 96px; height: 96px; background: #FFFFFF; border-radius: 96px; box-shadow: 0px -2px 4px rgba(216, 216, 216, 0.2), 0px 4px 4px rgba(216, 216, 216, 0.25);
    .slot{
      display: flex; flex-direction: column; align-items: center; justify-content: center; width: 96px; height: 96px;
      ._text{ font-size: 24px; line-height: 24px; color: $uni-color-secondary; }
    }
  }
}
</style>
